#!/usr/bin/python3

import serial
import time
import requests
import math

#下面这里我可以写一个try语句
try:
    ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=5)    #ttyUSB串口可在arduinoIDE查看
except:
    ser = serial.Serial('/dev/ttyUSB1', 9600, timeout=5)
    
num_fish = 2 #此处待修改
count = 0

TOKEN = "BBFF-TxNSic1Jsi3NNeoqjR0geZZHUd16HK"  # Put your TOKEN here
DEVICE_LABEL = "SmartFish"  # Put your device label here 
VARIABLE_LABEL_1 = "num_fish"  # Put your first variable label here
VARIABLE_LABEL_2 = "temp_val"  # Put your second variable label here
VARIABLE_LABEL_3 = "PH_val"  # Put your second variable label here
VARIABLE_LABEL_4 = "TU_val"  # Put your second variable label here

# read from Arduino
input = ser.read()
print ("Read input " + input.decode("utf-8") + " from Arduino")

def build_payload(variable_1, variable_2, variable_3, variable_4):
    # sending data
    value_1 = num_fish
    value_2 = temp_val
    value_3 = PH_val
    value_4 = TU_val

    payload = {variable_1: value_1,
               variable_2: value_2,
               variable_3: value_3,
               variable_4: value_4}

    return payload


def post_request(payload):
    # Creates the headers for the HTTP requests
    url = "http://industrial.api.ubidots.com"
    url = "{}/api/v1.6/devices/{}".format(url, DEVICE_LABEL)
    headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"}

    # Makes the HTTP requests
    status = 400
    attempts = 0
    while status >= 400 and attempts <= 5:
        req = requests.post(url=url, headers=headers, json=payload)
        status = req.status_code
        attempts += 1
        time.sleep(1)

    # Processes results
    if status >= 400:
        print("[ERROR] Could not send data after 5 attempts, please check \
            your token credentials and internet connection")
        return False

    print("[INFO] request made properly, your device is updated")
    return True


def main():
    payload = build_payload(
        VARIABLE_LABEL_1, VARIABLE_LABEL_2, VARIABLE_LABEL_3,VARIABLE_LABEL_4)

    print("[INFO] Attemping to send data")
    post_request(payload)
    print("[INFO] finished")


if __name__ == '__main__':
    while (True):
        # read response back from Arduino
        for i in range (0,3):
            input = ser.readline()
            if("Temp" in str(input)):
                temp_val = input
                temp_val = temp_val[12:-3]
                print("readTemp"+str(temp_val))
            elif("PH" in str(input)):
                PH_val = input
                PH_val = PH_val[9:-2]
                print("readPH"+str(PH_val))
            else:
                TU_val = input
                TU_val = TU_val[9:-5]
                print("readTU"+str(TU_val))
            print ("Read input back: " + str(input))
            count = count +1
        if(count%4 == 0):   
            main()
            count = 0
        time.sleep(1)

